import re, os, json
from website.website_base import WebSiteBase, FetchQueueItem, WebSiteDb
from bs4 import BeautifulSoup
from lib.log import DBG, INFO, ERROR, EXCEPTION
from lib.sqlite_ext import DBApiExt


class Zhazhiji(WebSiteBase):
    """
    """
    INDEX_URL = "https://zhazhijiav2gt.top"
    cmdpath = os.path.abspath(os.getcwd())
    DB = os.path.join(cmdpath, "website", "zhazhiji", "zhazhiji.db")
    SAVE_DIR = os.path.join(cmdpath, "website", "zhazhiji", "page")

    def __init__(self):
        super().__init__()

    @classmethod
    def _class_config(cls):
        class_list = [
            # {"id": "1", "name": "亚洲情色"},
            # {"id": "2", "name": "热门女优"},
            # {"id": "3", "name": "中文字幕"},
            {"id": "4", "name": "国产自拍"},
            # {"id": "5", "name": "无码专区"},
            # {"id": "6", "name": "伦理三级"},
            # {"id": "7", "name": "制服师生"},
            # {"id": "8", "name": "强奸乱伦"},
            # {"id": "9", "name": "丝袜美腿"},
            # {"id": "10", "name": "人妻熟女"},
            # {"id": "11", "name": "欧美性爱"},
            # {"id": "12", "name": "4K岛国"},
            # {"id": "13", "name": "韩国资源"},
            # {"id": "14", "name": "卡通动漫"},
            # {"id": "15", "name": "人妖人兽"},
            # {"id": "16", "name": "男同女同"},
            # {"id": "17", "name": "VR资源"},
            # {"id": "18", "name": "JAV高清"},
            # {"id": "19", "name": "亚洲精品"},
            # {"id": "20", "name": "风骚寡妇"},
            # {"id": "21", "name": "VR有码"},
            # {"id": "22", "name": "VR无码"},
            # {"id": "23", "name": "AI换脸"},
            # {"id": "24", "name": "骑兵有码"},
            # {"id": "25", "name": "步兵无码"},
            # {"id": "26", "name": "金发幼齿"},
            # {"id": "27", "name": "三级剧情"},
            # {"id": "28", "name": "韩美眉主"},
            # {"id": "29", "name": "韩美眉伦"},
            # {"id": "30", "name": "韩美眉综"},
            # {"id": "31", "name": "名优写真"},
            # {"id": "32", "name": "名优综艺"},
            # {"id": "33", "name": "名优中字"},
            # {"id": "34", "name": "无码破解"},
            # {"id": "54", "name": "精品推荐"},
            # {"id": "55", "name": "国产情色"},
            # {"id": "56", "name": "网红主播"},
            # {"id": "57", "name": "日本无码"},
            # {"id": "58", "name": "亚洲有码"},
            # {"id": "59", "name": "中文字幕"},
            # {"id": "60", "name": "欧美情色"},
            # {"id": "61", "name": "美乳巨乳"},
            # {"id": "62", "name": "强奸乱伦"},
            # {"id": "63", "name": "萝莉少女"},
            # {"id": "64", "name": "制服诱惑"},
            # {"id": "65", "name": "人妻熟女"},
            # {"id": "66", "name": "三级伦理"},
            # {"id": "67", "name": "成人动画"},
            {"id": "118", "name": "国产"},
            # {"id": "119", "name": "日韩"},
            # {"id": "120", "name": "欧美"},
            # {"id": "121", "name": "动漫"},
            # {"id": "122", "name": "麻豆番外篇"}
        ]
        return class_list

    def get_class_record_data(self):
        """
        获取所有分类记录信息

        :return:
        """

        class_list = self.__class__._class_config()

        class_list = list(map(lambda x: {
            "id": x['id'],
            "url": f"{self.INDEX_URL}/video_list/{x['id']}/1/index.html",
            "name": x['name'],
            "res_type": WebSiteDb.RES_TYPE_VIDEO,
            "page_count": 0,
            "res_count": 0
        }, class_list))

        return class_list

    def get_class_sub_page_url(self, class_index_url, page_num):
        """
        根据首页地址，获取其他分页地址

        :param page_num: 分页号
        :param class_index_url: 类型首页url
        :return: class_url
        """
        page_url = re.sub(r"/([0-9]+)/index\.html", rf"/{page_num}/index.html", class_index_url)
        return page_url

    def _parse_class_index_page(self, from_url, html_text):
        """

        :param from_url: html来自哪个url
        :param html_text: 解析的html内容
        :param dbapi: 解析进程的dbapi
        :param params: put fetch_queue的时候传的参数
        :return:
        """
        try:
            DBG(f"解析 url: {from_url}, size:{len(html_text)}")
            # "共34752条数据,当前1/2172页"
            # "共45371条数据&nbsp;当前:1/2161页"
            res_count = 0
            page_count = 0

            pattern = re.compile(r'<option value=([^>]*)>([^<]*)</option>')
            matches = pattern.findall(html_text)
            number = matches[-1][1]
            if number:
                page_count = int(number)
                res_count = page_count * 20

            return page_count, res_count

        except Exception as exc:
            # 处理其他异常情况
            ERROR(f"解析class index page 异常: {exc}")
            return 0, 0

    def _parse_class_page(self, from_url, html_text, params):
        # html_text = open("第1页.html")
        ins_datas = []
        try:
            DBG(f"解析 url: {from_url}, size:{len(html_text)}")
            class_id = params.get("id")
            pattern = r"app=(.+?)];"
            match = re.search(pattern, html_text)
            if match:
                list_str = match.group(0)
                list_str = list_str[4:-1]
                list_obj = json.loads(list_str)
                for i in range(len(list_obj)):
                    item = list_obj[i]
                    if len(item) < 4:
                        continue
                    res_id = self._get_res_id_from_href(item[0])
                    record = {
                        "id": res_id,
                        "class_id": class_id,
                        "name": item[3],
                        "res_type": WebSiteDb.RES_TYPE_VIDEO,
                        "head_image": item[1],
                        "url": item[0],
                        "parse": 0
                    }
                    ins_datas.append(record)

            DBG(f"解析出了{len(ins_datas)}个资源")
        except Exception as exc:
            EXCEPTION(f"解析class page 异常: {exc}")

        return ins_datas

    def _get_res_id_from_href(self, href):
        match = re.search(r'video_detail/(\d+)', href)
        res_id = None
        if match:
            res_id = match.group(1)
        else:
            ERROR(f"未解析出资源ID: {href}")

        return res_id

    def _parse_res_page(self, from_url, html_text, params):
        try:
            # DBG(f"解析 url: {from_url}, size:{len(html_text)}")

            result = re.search(r'play\(\'(.*?)\'', html_text)
            res_id = params.get("id")
            if result:
                play_href = result.group(1)
                DBG(f"解析出下载地址：{from_url}, {params}, {play_href}")
                return {"id": res_id, "video": play_href}
            else:
                ERROR(f"没有解析出下载地址：{from_url}, {params}")
                return None

        except Exception as exc:
            ERROR(f"解析资源播放页异常: {exc}")
            return None

    def save_image_callback(self, from_url, save_path):
        pass

    def run(self):
        # with open('aaaaa.html', 'r') as file:
        #     content = file.read()
        #
        #     self.parse_class_page(
        #         from_url="xxxx",
        #         html_text=content,
        #         dbapi=None,
        #         params={}
        #     )
        super().run()
